package net.app.help.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import net.app.help.R;
import net.app.help.db.DatabaseAdapter;
import net.app.help.model.Contact;
import net.app.help.model.Group;
import net.app.help.model.Message;
import net.app.help.services.Snemalec;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**		geo fix 46.335518 15.572769
 *		TO DO
 *	1. uredi login
 *			JE OK, 100% VARNO
 *	2. uredi pridobivanje naslova
 *			JE OK, NA EMULATORJU NE DELUJE
 *	3. uredi preferences in ustrezno branje ob spremembah
 *			JE OK, CALL IN RECORD MUTUALLY EXCLUSIVE
 *	4. uredi dizajn - popravki xmlov
 *			JE OK, SE NE PREKRIVA VEČ
 *	5. jsoup branje quota
 *			JE OK, VSAKIČ PREBERE NOVI QUOTE
 *	6. pripravi predstavitev - V PON
 *
 * */
public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

	private SharedPreferences prefs;
	private DatabaseAdapter da = new DatabaseAdapter(this);
	private GoogleApiClient mGoogleApiClient;
	private LocationManager lm;
	private Location mApproximateLocation;

	private String approximateLocation = "";
	private String longitude = "";
	private String latitude = "";
	private TextView quote, author;
	private TextView location;
	private Button help, stop, cancel;
	private ProgressBar mActivityIndicator;
	private LinearLayout helpLL, stopCancelLL;

	private TextView textview;
	private EditText edittext;
	private Button login;

	private boolean PINalreadySet = false;
	private String savedPIN = "";
	private String insertedPIN = "";
	private AlertDialog loginDialog;

	private ArrayList<Contact> contacts;
	private ArrayList<Group> groups;
	private ArrayList<Message> messages;
	private Map<Contact, Message> helpList;

	private MediaRecorder mediaRecorder;
	private int recordingCounter;

	private boolean call = false;
	private boolean record = false;
	private boolean sms = false;
	private boolean gps = false;
	private boolean loggedIn = false;
	private boolean workInProgress = false;
	private String callNumber = "0";


	/*FUNCTIONS*/
	private void setupViews() {

		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		helpLL = (LinearLayout) findViewById(R.id.act_main_ll_help);
		stopCancelLL = (LinearLayout) findViewById(R.id.act_main_ll_stop_cancel);

		mActivityIndicator = (ProgressBar) findViewById(R.id.act_main_pb);

		quote = (TextView) findViewById(R.id.act_main_tv_quote);
		author = (TextView) findViewById(R.id.act_main_tv_quote_author);
		location = (TextView) findViewById(R.id.act_main_tv_location);
		help = (Button) findViewById(R.id.act_main_b_help);
		help.setOnClickListener(helpListener);
		stop = (Button) findViewById(R.id.act_main_b_stop);
		stop.setOnClickListener(stopListener);
		cancel = (Button) findViewById(R.id.act_main_b_cancel);
		cancel.setOnClickListener(cancelListener);
		showHELPButton();
	}

	private void showAlertDialog(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
		builder.setTitle(title);
		builder.setMessage(message);
//				builder.setIcon(R.drawable.) //ALERT ICON TO BE SET
		builder.setNegativeButton(R.string.button_ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//NIČ
			}
		});
		builder.create();
		builder.show();
	}

	private void showHELPButton() {
		help.setVisibility(View.VISIBLE);
		helpLL.setVisibility(View.VISIBLE);
		stopCancelLL.setVisibility(View.GONE);
		stop.setVisibility(View.GONE);
		cancel.setVisibility(View.GONE);
	}

	private void showSTOPandCANCELButton() {
		helpLL.setVisibility(View.GONE);
		stopCancelLL.setVisibility(View.VISIBLE);
		help.setVisibility(View.GONE);
		stop.setVisibility(View.VISIBLE);
		cancel.setVisibility(View.VISIBLE);
	}

	private void obtainDailyQuote() {
//		CONNECT SOMEWHERE ONLINE AND FETCH QUOTE
		new GetQuoteTask().execute();
	}

	private void readPreferences() {

		SharedPreferences sPrefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs = sPrefs;

		//ZA TESTIRANJE BRIŠI PIN
//		SharedPreferences.Editor editor = prefs.edit();
//		editor.remove(getString(R.string.key_pin));
//		editor.apply();

//		editor.putBoolean(getString(R.string.key_record), true);
//		editor.putString(getString(R.string.key_contact), "070799929");
//		editor.putBoolean(getString(R.string.key_gps), true);
//		editor.apply();

		if (prefs.getBoolean( getString(R.string.key_call), false) ) {
			//call contact
			call = true;
		} else {
			call = false;
		}
		if (call) {
			//call contact number
			callNumber = prefs.getString(getString(R.string.key_contact), "0");
			Log.e("readPreferences","callNumber="+callNumber);
		}
		if (prefs.getBoolean( getString(R.string.key_record), false) ) {
			//record sound
			record = true;
		} else {
			record = false;
		}
		if (prefs.getBoolean( getString(R.string.key_gps), false) ) {
			//check GPS coordinates
			gps = true;
		} else {
			gps = false;
		}
		if (prefs.getBoolean( getString(R.string.key_sms), false) ) {
			//send SMS messages
			sms = true;
		} else {
			sms = false;
		}
		if (prefs.getBoolean( getString(R.string.key_login), false)) {
			loggedIn = true;
		} else {
			loggedIn = false;
		}
		if (!prefs.getString( getString(R.string.key_pin), String.valueOf("")).equals("") ) {
			//PREVERI IN SHRANI PIN
			PINalreadySet = true;
			savedPIN = prefs.getString(getString(R.string.key_pin), "");
			Log.e("PINalreadySet", String.valueOf(PINalreadySet));
			Log.e("savedPIN", savedPIN);
		} else {
			PINalreadySet = false;
		}
		if (prefs.getBoolean( getString(R.string.key_working), false )) {
			workInProgress = true;
		} else {
			workInProgress = false;
		}
		//get recording number
		recordingCounter = prefs.getInt( getString(R.string.key_recording), 0);
		Log.e("readPreferences", "call="+call+" record="+record+" gps="+gps+" sms="+sms+" recordingCounter="+recordingCounter);
	}

	private int defineHelpList() {
		helpList = new HashMap<Contact, Message>();
		da.openToRead();
		contacts = da.getAllContacts();
		groups = da.getAllGroups();
		messages = da.getAllMessages();
		da.close();

		int counter = 0;
		Contact c = null;
		Group g = null;
		Message m = null;
		for (int i=0; i<contacts.size(); i++) {
			c = contacts.get(i);
			if (c.getId_grp() == 0 && c.getId_msg() == 0) {
				//SKIP CONTACT
			} else {
				if (c.getId_grp() != 0) {
					//SEND GROUP MESSAGE
					for (int j=0; j<groups.size(); j++) {
						if (c.getId_grp() == groups.get(j).getId()) {
							g = groups.get(j);
							//FIND BOUND MESSAGE AND SEND
							for (int l=0; l<messages.size(); l++) {
								if (g.getId_msg() == messages.get(l).getId()) {
									m = messages.get(l);
									//SEND MESSAGE - ADD TO helpLIST
									helpList.put(c, m);
									counter++;
								}
							}
						}
					}
				} else {
					if (c.getId_msg() != 0) {
						//SEND INDIVIDUAL MESSAGE
						for (int k=0; k<messages.size(); k++) {
							if (c.getId_msg() == messages.get(k).getId()) {
								m = messages.get(k);
								//SEND MESSAGE - ADD TO helpLIST
								helpList.put(c, m);
								counter++;
							}
						}
					}
				}
			}
		}
		Log.e("defineHELPList POPULATED", "counter="+counter+" helpList.size="+helpList.size());
		return counter;
	}

	/**Iterates through helpList populated with Contacts and their Messages and sends SMS messages.*/
	private void sendSMSMessages() {
		SmsManager smsManager = SmsManager.getDefault();
		int counter = defineHelpList();
		String locationLine = "";
		for (Map.Entry<Contact, Message> contactMessageEntry : helpList.entrySet()) {
			if (helpList.size() != 0) {
//				Log.e("sendSMSMessages defineHelpList","size != 0");
				if (gps && !longitude.equals("") && !latitude.equals("")) {
					locationLine = "\r\n" + "My current location: " +
									"\r\n" + "Longitude: " + longitude +
									"\r\n" + "Latitude: " + latitude;
					Log.d("sendSMSMessages", "locationLine="+locationLine);
					if (!approximateLocation.equals("")) {
						locationLine = "\r\n" + "My current location: " +
										approximateLocation;
						Log.d("sendSMSMessages", "locationLine="+locationLine);
						smsManager.sendTextMessage(contactMessageEntry.getKey().getTel().toString(),
								null,
								contactMessageEntry.getValue().getTitle() +
										"\r\n" + contactMessageEntry.getValue().getContent() +
										locationLine,
								null,
								null);
						Log.v(contactMessageEntry.getKey().getName() + " TEL:" + contactMessageEntry.getKey().getTel(),
								"TITLE: " + contactMessageEntry.getValue().getTitle() +
										" CONTENT: " + contactMessageEntry.getValue().getContent() +
										"locationLine");
					} else {
						smsManager.sendTextMessage(contactMessageEntry.getKey().getTel().toString(),
								null,
								contactMessageEntry.getValue().getTitle() +
										"\r\n" + contactMessageEntry.getValue().getContent() +
										locationLine,
								null,
								null);
						Log.v(contactMessageEntry.getKey().getName() + " TEL:" + contactMessageEntry.getKey().getTel(),
										"TITLE: " + contactMessageEntry.getValue().getTitle() +
										" CONTENT: " + contactMessageEntry.getValue().getContent() +
										"locationLine");
					}
				} else {
					smsManager.sendTextMessage(contactMessageEntry.getKey().getTel().toString(),
							null,
							contactMessageEntry.getValue().getTitle() + "\r\n" + contactMessageEntry.getValue().getContent(),
							null,
							null);
					Log.v(contactMessageEntry.getKey().getName() + " TEL:" + contactMessageEntry.getKey().getTel(),
									"TITLE: " + contactMessageEntry.getValue().getTitle() +
									" CONTENT: " + contactMessageEntry.getValue().getContent());
				}
			}
		}
		Toast.makeText(MainActivity.this, counter+" SMS messages sent!", Toast.LENGTH_LONG).show();
	}

	private void sentReturnSMSMessages(String title, String content) {
		SmsManager smsManager = SmsManager.getDefault();
		int counter = defineHelpList();
		for (Map.Entry<Contact, Message> contactMessageEntry : helpList.entrySet()) {
			smsManager.sendTextMessage(contactMessageEntry.getKey().getTel().toString(),
					null,
					title + "\r\n" + content,
					null,
					null);
			Log.v(contactMessageEntry.getKey().getName()+" TEL:"+contactMessageEntry.getKey().getTel(),"TITLE: "+title+ " CONTENT: "+content);
		}
		Toast.makeText(MainActivity.this, counter+" SMS messages sent!", Toast.LENGTH_LONG).show();
	}

	/**Starts recording sound.
	 * Saves the file to the SD card/default directory.
	 * fileName = "HELP_Recording_##.amr" ; ## = recordingCounter
	 * */
	private void recordSound() {
		Intent recordSound = new Intent(this, Snemalec.class);
		recordSound.setAction("net.app.help.services.action.REC");
		recordSound.putExtra("net.app.help.services.extra.RECCOUNTER", recordingCounter);
		startService(recordSound);
	}

	private void stopRecordingSound() {
		Intent saveRecording = new Intent(this, Snemalec.class);
		saveRecording.setAction("net.app.help.services.action.SAV");
		saveRecording.putExtra("net.app.help.services.extra.RECCOUNTER", recordingCounter);
//		startSer
	}

	/**Initiates a call to the chosen contact */
	public void callContact() {
//		if (prefs.getBoolean( getString(R.string.key_call), false) ) {
//			String contactNumber = prefs.getString(getString(R.string.key_contact), "0");
//			//check contact to call
			if (!callNumber.equals("0")) {
				Intent callIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + callNumber));
				startActivity(callIntent);
				//HERE IT MIGHT BE POSSIBLE TO ALSO RECORD THIS CALL / IS IT ANYWAY?
			} else {
				Toast.makeText(MainActivity.this, "Choose a contact to call in Settings", Toast.LENGTH_SHORT).show();
			}
//		}
	}

	private void obtainApproximateLocation() {
		//EVO TUKAJ JE TREBA IMPLEMENTIRATI ŠE PRETVARJANJE LONGITUDE IN LATITUDE V APPROX ADDRESS IN GA PRIKAZATI

		// Ensure that a Geocoder services is available
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent()) {
			// Show the activity indicator
//			mActivityIndicator.setVisibility(View.VISIBLE);
            /*
             * Reverse geocoding is long-running and synchronous.
             * Run it on a background thread.
             * Pass the current location to the background task.
             * When the task finishes,
             * onPostExecute() displays the address.
             */
			//POTREBNO ŠE PREVERITI ALI SPLOH IMAMO KAKŠNE PODATKE O LOKACIJI; ČE JIH NI, NI KAJ ZA OBDELOVAT.
			if (mApproximateLocation != null) {
				(new GetAddressTask(this)).execute(mApproximateLocation);
			}else {
				//pač nič
			}
		}

	}

	private void showCancelMessageDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.dialog_return_message_title));
		View v = getLayoutInflater().inflate(R.layout.dialog_add_message, null);
		final EditText titleET = (EditText) v.findViewById(R.id.dialog_add_msg_et_title);
		final EditText contentET = (EditText) v.findViewById(R.id.dialog_add_msg_et_content);
		builder.setView(v);
		builder.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Toast.makeText(MainActivity.this, "Messages not sent, repeat the process to send cancel message.", Toast.LENGTH_LONG).show();
			}
		});
		builder.setPositiveButton(R.string.button_send, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String title = titleET.getText().toString();
				String content = contentET.getText().toString();
				if (title != null && content != null && !title.equals("") && !content.equals("")) {
					sentReturnSMSMessages(title, content);
				} else {
					Toast.makeText(MainActivity.this, "Error" + "\r\n" + "Fill out return message title and content.", Toast.LENGTH_LONG).show();
//					showAlertDialog("Error", "Fill out return message title and content.");
				}
			}
		});
		AlertDialog returnMessageDialog = builder.create();
		returnMessageDialog.setCancelable(false);
		returnMessageDialog.show();
	}

	/**HELP Button actions:
	 * - readsPreferences
	 * - starts recording sound in the background
	 * - obtains GPS coordinates
	 * - collects DB data and sends SMS messages + coordinates?
	 * - initiates a call
	 * - hides HELP button and shows others
	 * - after all is done hides app
	 * - */
	private View.OnClickListener helpListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if (gps) {
				reconnectAndRefreshApproximateLocation();
//				if (approximateLocation.equals("")) {
				obtainApproximateLocation();
//				}
			}
			if (sms)
				sendSMSMessages();
			if (record)
				recordSound();    //doesn't seem to work on the emulator
			if (call)
				callContact();
			//Show progress bar while actions are executing.
			showSTOPandCANCELButton();

			//After progress bar finishes, call onPause/onStop and hide the App
//			Toast.makeText(MainActivity.this, "HELP!", Toast.LENGTH_SHORT).show();
			SharedPreferences.Editor editor = prefs.edit();
			editor.putBoolean(getString(R.string.key_working), true);
			editor.apply();
		}
	};

	/**STOP Button actions:
	 * - Stops recording sound
	 * - shows HELP button
	 * */
	private View.OnClickListener stopListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if (gps)
				disconnectGoogleApiClient();
			if (record)
				stopRecordingSound();	//doesn't seem to work on the emulator
			showHELPButton();

			SharedPreferences.Editor editor = prefs.edit();
			editor.putBoolean(getString(R.string.key_working), false);
			editor.apply();
		}
	};

	/**CANCEL Button actions:
	 * - Stops recording sound
	 * - Opens AlertDialog for user to write a response to all contacts contacted in the first place*/
	private View.OnClickListener cancelListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if (gps)
				disconnectGoogleApiClient();
			if (record)
				stopRecordingSound();	//doesn't seem to work on the emulator
			//SHOW DIALOG TO COMPOSE RETURN MESSAGE AND SEND IT TO ALL CONTACTED
			if (sms)
				showCancelMessageDialog();
			showHELPButton();

			SharedPreferences.Editor editor = prefs.edit();
			editor.putBoolean(getString(R.string.key_working), false);
			editor.apply();
		}
	};

	private View.OnClickListener loginListener = new View.OnClickListener() {
		@Override			/*DialogInterface dialog, int which*/
		public void onClick(View v) {
			insertedPIN = edittext.getText().toString();
			if (PINalreadySet) {
				if (insertedPIN.equals(savedPIN)) {
					Toast.makeText(MainActivity.this, "Login successful", Toast.LENGTH_SHORT).show();
					loginDialog.dismiss();

					SharedPreferences.Editor editor = prefs.edit();
//		editor.remove(getString(R.string.key_pin));
					editor.putBoolean(getString(R.string.key_login), true);
					editor.apply();
				} else {
					Toast.makeText(MainActivity.this, "Wrong PIN", Toast.LENGTH_SHORT).show();
				}
			} else {
				if (insertedPIN.equals("")) {
					Toast.makeText(MainActivity.this, "Invalid PIN", Toast.LENGTH_SHORT).show();
				} else {
					//SAVE PIN TO PREFERENCES
					SharedPreferences.Editor editor = prefs.edit();
					editor.putString(getString(R.string.key_pin), insertedPIN);
					editor.putBoolean(getString(R.string.key_login), true);
					editor.apply();
					Toast.makeText(MainActivity.this, "PIN chosen", Toast.LENGTH_LONG).show();
					loginDialog.dismiss();
				}
			}
		}
	};

	/**Metoda, ki se bo klicala vedno pred situacijo, kjer bi morda bil potreben login.
	 * Login je potreben le ob prvem zagonu aplikacije.
	 * Po uspešnem loginu se v preferences shrani vrednost loggedIn = true, ki določa, da je bil login opravljen.
	 * Ta metoda nato preveri ali je bil login opravljen in na podlagi ugotovitve prikaže login dialog ali ne.
	 * V onDestroy metodi se vrednost v preferences nastavi na loggedIn = false.
	 * */
	private boolean checkIfLoggedIn() {
		if (prefs.getBoolean( getString(R.string.key_login), false)) {
			loggedIn = true;
		} else {
			loggedIn = false;
		}
		return loggedIn;
	}

	private void login() {
		Log.e("LOGIN","pred metodo");
		if (!checkIfLoggedIn()) {
			Log.e("LOGIN","v metodi - NOT LOGGED IN");
			AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
			builder.setTitle("LOGIN");
			builder.setMessage("Login to continue");
			View v = getLayoutInflater().inflate(R.layout.fragment_login, null, false);
			textview = (TextView) v.findViewById(R.id.frag_log_tv);
			edittext = (EditText) v.findViewById(R.id.frag_log_et);
			login = (Button) v.findViewById(R.id.frag_log_b);
			login.setOnClickListener(loginListener);
			if (PINalreadySet) {
				textview.setText(getString(R.string.frag_login_enter_pin));
				login.setText(getString(R.string.button_login));
			} else {
				textview.setText(getString(R.string.frag_login_select_pin));
				login.setText(getString(R.string.button_confirm));
			}
			builder.setView(v);
			loginDialog = builder.create();
			loginDialog.setCancelable(false);
			loginDialog.show();
		}
	}

	protected synchronized void buildGoogleApiClient() {
		if (mGoogleApiClient == null) {
			mGoogleApiClient = new GoogleApiClient.Builder(this)
					.addConnectionCallbacks(this)
					.addOnConnectionFailedListener(this)
					.addApi(LocationServices.API)
					.build();
			Log.e("onCreate buildGoogleApiClient","mGoogleApiClient BUILT!");
		} else {
			reconnectAndRefreshApproximateLocation();
		}
		Log.e("onCreate buildGoogleApiClient","mGoogleApiClient BUILD AGAIN?");
	}

	protected synchronized void connectGoogleApiClient() {
		if (mGoogleApiClient != null && !mGoogleApiClient.isConnected())
			mGoogleApiClient.connect();
		Log.e("connectGoogleApiClient","mGoogleApiClient connected AGAIN?");
	}

	protected synchronized void disconnectGoogleApiClient() {
		if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
			mGoogleApiClient.disconnect();
		Log.e("disconnectGoogleApiClient","mGoogleApiClient disconnected!");
	}

	protected synchronized void reconnectAndRefreshApproximateLocation() {
		if (mGoogleApiClient != null) {
			mGoogleApiClient.reconnect();
			Log.e("reconnectGoogleApiClient","mGoogleApiClient RECONNECTED!");
		}
		Log.e("reconnectGoogleApiClient","mGoogleApiClient reconnected AGAIN?");
	}

	@Override
	protected void onPause() {
		Log.e("LOGIN TEST","onPause");
		super.onPause();
	}

	@Override
	protected void onResume() {
		Log.e("LOGIN TEST","onResume");
		super.onResume();
	}

	@Override
	protected void onPostResume() {
		Log.e("LOGIN TEST","onPostResume");
//		SharedPreferences.Editor editor = prefs.edit();
////		editor.remove(getString(R.string.key_pin));
//		editor.putBoolean(getString(R.string.key_login), true);
//		editor.apply();
		super.onPostResume();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Log.e("LOGIN TEST","onRestart");
		readPreferences();
		reconnectAndRefreshApproximateLocation();
		if (mGoogleApiClient != null && mApproximateLocation != null) {
			if (approximateLocation.equals("")) {
				obtainApproximateLocation();
			}
		}
		login();
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.e("LOGIN TEST", "onStop");
//		onFirstStart = true;
		SharedPreferences.Editor editor = prefs.edit();
//		editor.remove(getString(R.string.key_pin));
		editor.putBoolean(getString(R.string.key_login), false);
		editor.apply();
		disconnectGoogleApiClient();
		if (loginDialog != null)
			loginDialog.dismiss();
	}

//	public boolean determineVersionIsIceCreamSandwichOrNewer() {
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
//			return true;
//		} else {
//			return false;
//		}
//	}
//
	public void setSupportActionBarLogo() {
		getSupportActionBar().setDisplayShowHomeEnabled(true);
//		getSupportActionBar().setDisplayUseLogoEnabled(true);
//		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setIcon(R.drawable.help_app_icon);
//		getSupportActionBar().setLogo(R.drawable.help_app_icon);
	}

//	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
//	public void setActionBarLogo() {
//		getActionBar().setDisplayShowHomeEnabled(true);
//		getActionBar().setDisplayUseLogoEnabled(true);
//		getActionBar().setIcon(R.drawable.help_app_icon);
//		getActionBar().setLogo(R.drawable.help_app_icon);
//	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Log.e("LOGIN TEST", "onCreate");

//		if (determineVersionIsIceCreamSandwichOrNewer()) {
//			setActionBarLogo();
//		} else {
			setSupportActionBarLogo();
//		}

		buildGoogleApiClient();
		connectGoogleApiClient();
		obtainDailyQuote();
		if (mGoogleApiClient != null && mApproximateLocation != null) {
			if (approximateLocation.equals("")) {
				obtainApproximateLocation();
			}
		}
		setupViews();

		readPreferences();

		if (workInProgress) {
			showSTOPandCANCELButton();
		}

		login();
	}

	@Override
	protected void onDestroy() {
		SharedPreferences.Editor editor = prefs.edit();
//		editor.remove(getString(R.string.key_pin));
		editor.putBoolean(getString(R.string.key_login), false);
		editor.apply();
		super.onDestroy();
		Log.e("LOGIN TEST","onDestroy");
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.

		// Handle presses on the action bar items
		switch (item.getItemId()) {
			case R.id.action_contacts:
				Intent c = new Intent(this, ContactsActivity.class);
				startActivity(c);
				return true;
			case R.id.action_groups:
				Intent g = new Intent(this, GroupsActivity.class);
				startActivity(g);
				return true;
			case R.id.action_messages:
				Intent m = new Intent(this, MessagesActivity.class);
				startActivity(m);
				return true;
			case R.id.action_settings:
				Intent i = new Intent(this, SettingsActivity.class);
				startActivity(i);
				return true;
			case R.id.action_instructions:
				Intent ins = new Intent(this, InstructionsActivity.class);
				startActivity(ins);
				return true;
			case R.id.action_send_okay_sms:
				showCancelMessageDialog();
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}

	}

	@Override
	public void onConnected(Bundle bundle) {
		mApproximateLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

//		Toast.makeText(MainActivity.this, "onConnected", Toast.LENGTH_SHORT);
		if (mGoogleApiClient == null) {
			Log.e("mGoogleApiClient"," IS NULL");
		}
		if (mApproximateLocation == null) {
			Log.e("mApproximateLocation"," IS NULL");
		}
		Log.e("onConnected", "!!! GOT LOCATION");
		if (mApproximateLocation != null) {
			latitude = String.valueOf(mApproximateLocation.getLatitude());
			longitude = String.valueOf(mApproximateLocation.getLongitude());
			location.setText("Latitude: " + String.valueOf(mApproximateLocation.getLatitude()) + " Longitude: " + String.valueOf(mApproximateLocation.getLongitude()));
			Log.e("onConnected", "!!! GOT LOCATION" + "Latitude="+mApproximateLocation.getLatitude()+" | Longitude="+mApproximateLocation.getLongitude());
			obtainApproximateLocation();
//			Toast.makeText(MainActivity.this, "Latitude: " + String.valueOf(mApproximateLocation.getLatitude()) + " Longitude: " + String.valueOf(mApproximateLocation.getLongitude()), Toast.LENGTH_SHORT).show();
		} else {
			Log.e("onConnected", "!!! GOT LOCATION - Not available");
			location.setText("Not available.");
		}
	}

	@Override
	public void onConnectionSuspended(int i) {
		//NIČ ali mogoče javi da GPS ni na voljo in vseeno pošlji SMSe?
//		Toast.makeText(MainActivity.this, "onConnectionSuspended", Toast.LENGTH_SHORT);
		Log.e("onConnectionSuspended", "!!! int i="+i);
	}

	@Override
	public void onConnectionFailed(ConnectionResult connectionResult) {
		//nič
//		Toast.makeText(MainActivity.this, "onConnectionFailed", Toast.LENGTH_SHORT);
		Log.e("onConnectionFailed", "!!!");
	}

	/**
	 * A subclass of AsyncTask that calls getFromLocation() in the
	 * background. The class definition has these generic types:
	 * Location - A Location object containing
	 * the current location.
	 * Void     - indicates that progress units are not used
	 * String   - An address passed to onPostExecute()
	 */
	private class GetAddressTask extends AsyncTask<Location, Void, String> {

		Context mContext;

		public GetAddressTask(Context context) {
			super();
			mContext = context;
		}
//		...
		/**
		 * Get a Geocoder instance, get the latitude and longitude
		 * look up the address, and return it
		 *
		 * @params params One or more Location objects
		 * @return A string containing the address of the current
		 * location, or an empty string if no address can be found,
		 * or an error message
		 */
		@Override
		protected String doInBackground(Location... params) {
			Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
			// Get the current location from the input parameter list
			Location loc = params[0];
			// Create a list to contain the result address
			List<Address> addresses = null;
			try {
                /*
                 * Return 1 address.
                 */
				addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
			} catch (IOException e1) {
				Log.e("LocationSampleActivity", "IO Exception in getFromLocation()");
				e1.printStackTrace();
				return ("IO Exception trying to get address");
			} catch (IllegalArgumentException e2) {
				// Error message to post in the log
				String errorString = "Illegal arguments " + Double.toString(loc.getLatitude()) + " , " + Double.toString(loc.getLongitude()) + " passed to address service";
				Log.e("LocationSampleActivity", errorString);
				e2.printStackTrace();
				return errorString;
			}
			// If the reverse geocode returned an address
			if (addresses != null && addresses.size() > 0) {
				// Get the first address
				Address address = addresses.get(0);
                /*
                 * Format the first line of address (if available),
                 * city, and country name.
                 */
				String addressText = String.format(
						"%s, %s, %s",
						// If there's a street address, add it
						address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
						// Locality is usually a city
						address.getLocality(),
						// The country of the address
						address.getCountryName());
				// Return the text
				return addressText;
			} else {
				return "No address found";
			}
		}
		/**
		 * A method that's called once doInBackground() completes. Turn
		 * off the indeterminate activity indicator and set
		 * the text of the UI element that shows the address. If the
		 * lookup failed, display the error message.
		 */
		@Override
		protected void onPostExecute(String address) {
			// Set activity indicator visibility to "gone"
//			mActivityIndicator.setVisibility(View.GONE);
			// Display the results of the lookup.
			approximateLocation = address;
			location.setText(String.valueOf(approximateLocation));
			Log.d("GetAddressTask onPostExecute","approximateLocation="+approximateLocation);
		}
//		...
	}

	private class GetQuoteTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... params) {
//			CREATE Jsoup Document and parse quotes, return random one.

			Document doc = null;
			try {
				doc = Jsoup.connect("http://www.healthyplace.com/insight/quotes/quotes-on-abuse").userAgent("Chrome").get();
			} catch (IOException e) {
				e.printStackTrace();
				Log.e("GetQuoteTask doInBackground","ERROR; doc = null");
			}
			if (doc != null) {
				Elements quotes = doc.getElementsByTag("em");
				List<Element> quotesList = quotes.subList(0, quotes.size());
				Collections.shuffle(quotesList);
				return quotesList.get(0).text();
			} else
				return "You can get out.";
		}

		@Override
		protected void onPostExecute(String s) {
			if (!s.equals("")) {
				quote.setText(String.valueOf(s));
				author.setText(String.valueOf(""));
			}
			Log.d("GetQuoteTask onPostExecute","Quote nastavljen.");
		}
	}

//	private class ExecuteHELPTask extends AsyncTask<Void, Void, String> {
//
//		@Override
//		protected String doInBackground(Void... params) {
//
//			while (approximateLocation.equals("")) {
//
//			}
//
//			return "";
//		}
//
//		@Override
//		protected void onPostExecute(String s) {
//			Log.d("ExecuteHELPTask onPostExecute","Prožijo se še ostale operacije.");
//			if (sms)
//				sendSMSMessages();
//			if (record)
//				recordSound();	//doesn't seem to work on the emulator
//			if (call)
//				callContact();
//		}
//	}

}
